package com.witframework.security.dos;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class DosFilter implements Filter{
	private DosFilterUtil dos;
	private int times;
	private static String errorPage=null;

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException
    {
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)res;
		if(errorPage==null)
			errorPage=request.getContextPath()+"/common/error.jsp?code=dos";
		try{
			dos.filter(request,response);
			chain.doFilter(req, res);
		}catch(DosException dosec){
			//error(request,response);
			response.setContentType("text/plain;charset=utf-8");
			response.getWriter().println(dosec.getMessage());
		}

    }
	public void destroy() {
		dos=null;
	}
	public void init(FilterConfig filterConfig) throws ServletException {
		dos=DosFilterUtil.getInstance();
		if (filterConfig != null) {
			String value = filterConfig.getInitParameter("times");
			if (value != null) {
				times =Integer.parseInt(value);
			} else {
				times = 300;
			}
		}
		dos.setTimes(times);

	}
	private void error(HttpServletRequest request,HttpServletResponse response) throws IOException {
		if(errorPage!=null){
			try{
			response.sendRedirect(errorPage);
			}catch(Exception e){}
		}
	}

}


